package com.ruoyi.cms.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.aliyun.green20220302.Client;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.api.feign.ContentModerationService;
import com.ruoyi.cms.entity.domain.ModelCollection;
import com.ruoyi.cms.entity.req.ModelCollectionListReq;
import com.ruoyi.cms.entity.req.ModelListReq;
import com.ruoyi.cms.entity.resp.ModelCollectionListResp;
import com.ruoyi.cms.entity.resp.ModelListResp;
import com.ruoyi.cms.service.ModelService;
import com.ruoyi.common.context.AppUserContext;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.enums.cms.CmsErrorCode;
import com.ruoyi.common.exception.modules.CmsException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.cms.mapper.ModelCollectionMapper;
import com.ruoyi.cms.service.ModelCollectionService;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;
import java.util.List;

/**
 * 模型合集Service业务层处理
 */
@Service
@Slf4j
public class ModelCollectionServiceImpl implements ModelCollectionService {

    @Autowired
    private ModelCollectionMapper modelCollectionMapper;
    @Autowired
    private ModelService modelService;
    @Autowired
    private ContentModerationService contentModerationService;

    private static final Long collectionModelNum = 4L;

    @Override
    public R<Page<ModelCollectionListResp>> list(ModelCollectionListReq req) {

        Page<ModelCollection> page = new Page<>(req.getCurrent(), req.getSize());

        LambdaQueryWrapper<ModelCollection> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StrUtil.isNotBlank(req.getModelCollectionName()), ModelCollection::getName, req.getModelCollectionName());
        queryWrapper.eq(req.getUserId() != null, ModelCollection::getCreator, req.getUserId());
        queryWrapper.eq(ModelCollection::getVisible, 2);
        queryWrapper.eq(ModelCollection::getDeleted, 0);
        page = modelCollectionMapper.selectPage(page, queryWrapper);

        if (CollUtil.isEmpty(page.getRecords())) {
            return R.ok(new Page<>());
        }

        Page<ModelCollectionListResp> collectionListRespPage = (Page<ModelCollectionListResp>) page.convert(modelCollection -> {
            ModelCollectionListResp modelCollectionListResp = new ModelCollectionListResp();
            modelCollectionListResp.setId(modelCollection.getId());
            modelCollectionListResp.setName(modelCollection.getName());
            modelCollectionListResp.setCreateTime(modelCollection.getCreateTime());

            ModelListReq modelListReq = new ModelListReq();
            modelListReq.setCollectionId(modelCollection.getId());
            modelListReq.setCurrent(1L);
            modelListReq.setSize(collectionModelNum);
            R<Page<ModelListResp>> modelListPage = modelService.queryModelByCollectionId(modelListReq);

            modelCollectionListResp.setModelCount((int) modelListPage.getData().getTotal());
            modelCollectionListResp.setModelList(modelListPage.getData().getRecords());

            return modelCollectionListResp;
        });

        return R.ok(collectionListRespPage);
    }

    @Override
    public R<Page<ModelCollectionListResp>> myCollectionList(ModelCollectionListReq req) {

        Page<ModelCollection> page = new Page<>(req.getCurrent(), req.getSize());

        LambdaQueryWrapper<ModelCollection> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StrUtil.isNotBlank(req.getModelCollectionName()), ModelCollection::getName, req.getModelCollectionName());
        queryWrapper.eq(ModelCollection::getCreator, AppUserContext.getUser().getUserId());
        queryWrapper.eq(ModelCollection::getDeleted, 0);
        page = modelCollectionMapper.selectPage(page, queryWrapper);

        if (CollUtil.isEmpty(page.getRecords())) {
            return R.ok(new Page<>());
        }

        Page<ModelCollectionListResp> collectionListRespPage = (Page<ModelCollectionListResp>) page.convert(modelCollection -> {
            ModelCollectionListResp modelCollectionListResp = new ModelCollectionListResp();
            modelCollectionListResp.setId(modelCollection.getId());
            modelCollectionListResp.setName(modelCollection.getName());
            modelCollectionListResp.setCreateTime(modelCollection.getCreateTime());

            ModelListReq modelListReq = new ModelListReq();
            modelListReq.setCollectionId(modelCollection.getId());
            modelListReq.setCurrent(1L);
            modelListReq.setSize(collectionModelNum);
            R<Page<ModelListResp>> modelListPage = modelService.queryMyModelByCollectionId(modelListReq);

            modelCollectionListResp.setModelCount((int) modelListPage.getData().getTotal());
            modelCollectionListResp.setModelList(modelListPage.getData().getRecords());

            return modelCollectionListResp;
        });

        return R.ok(collectionListRespPage);
    }

    @Override
    public R<?> add(ModelCollection modelCollection) {
        //审核标题
        Client client;
        try {
            client = contentModerationService.createSZClient();
        } catch (Exception e) {
            log.error("modelCollection add moderation error", e);
            throw new CmsException("modelCollection add moderation error");
        }
        if (!contentModerationService.textModeration(modelCollection.getName(), client)) {
            throw new CmsException(CmsErrorCode.TEXT_VIOLATION.getCode(), CmsErrorCode.TEXT_VIOLATION.getMsg());
        }

        Long userId = AppUserContext.getUser().getUserId();
        Date now = new Date();
        modelCollection.setCreator(userId);
        modelCollection.setUpdater(userId);
        modelCollection.setCreateTime(now);
        modelCollection.setUpdateTime(now);

        modelCollectionMapper.insert(modelCollection);
        return R.ok();
    }

    @Override
    public R<?> delete(List<String> ids) {
        ids.forEach(id -> {
            ModelCollection modelCollection = modelCollectionMapper.selectById(id);
            modelService.collectionCheck(modelCollection);

            modelCollectionMapper.deleteById(id);
        });
        return R.ok();
    }

    @Override
    public R<?> update(ModelCollection modelCollection) {
        //审核标题
        Client client;
        try {
            client = contentModerationService.createSZClient();
        } catch (Exception e) {
            log.error("modelCollection update moderation error", e);
            throw new CmsException("modelCollection update moderation error");
        }
        if (!contentModerationService.textModeration(modelCollection.getName(), client)) {
            throw new CmsException(CmsErrorCode.TEXT_VIOLATION.getCode(), CmsErrorCode.TEXT_VIOLATION.getMsg());
        }

        ModelCollection modelCollection2 = modelCollectionMapper.selectById(modelCollection.getId());
        modelService.collectionCheck(modelCollection2);

        modelCollection2.setName(modelCollection.getName());
        modelCollection2.setVisible(modelCollection.getVisible());
        modelCollection2.setUpdater(AppUserContext.getUser().getUserId());
        modelCollection2.setUpdateTime(new Date());
        modelCollectionMapper.updateById(modelCollection2);
        return R.ok();
    }


}
